package com.wehealth;


import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.adapter.Adapter_PlanDay_info_new;
import com.wehealth.adapter.Adapter_PlanDay_new;
import com.wehealth.dm.DM_PlanDay_info_new;
import com.wehealth.dm.DM_PlanDay_new;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TimePicker;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("ValidFragment")
public class Plan_Day_info extends Fragment {

	private ListView lv_planDay;
	MainActivity activity;
	private static  String JSONResult;
	private static final int NET_ERROR = -100;
	private String  itemID;
	
	private TextView mCarbTV;//food_carbohydrate_value;
	private TextView mFatTV;//food_fat_value
	private TextView mProteinTV;
	private TextView mCelluloseTV;// food_cellulose_value
	private DM_PlanDay_info_new planInfo;
	private CheckBox  mRemindCB;
	private String state ="0";
	private TextView mRemindTime;
	private ImageButton mRemindTimeSet;
	private AlertDialog mDialog;
	private String mRemindTimeNew;
	private TextView mChangeInfoTv;
	private TextView mDoFlag;
	private boolean isCompleted =false;
	private int weekday;
		
	public  Plan_Day_info()
	{

	}
	
	
	public  Plan_Day_info(String ID,String state,int weekday)
	{
		itemID = ID;
		if(state.equals("0")){
			isCompleted =false;
		}else{
			isCompleted =true;
		}
		this.weekday = weekday;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.plan_day_info, null);
	}
	
	
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
	    activity = (MainActivity)getActivity();
	    MobclickAgent.openActivityDurationTrack(false);
		
		TextView title=(TextView)activity.findViewById(R.id.header_title);
		String titlename = activity.getString(R.string.play_day_info);
		title.setText(titlename);
		Button bBack = (Button) activity.findViewById(R.id.header_bBack);
	    bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
				    activity.switchContentHome();
				}
			});
	    
		lv_planDay = (ListView)activity.findViewById(R.id.play_day_info_list);
		mCarbTV =(TextView)activity.findViewById(R.id.food_carbohydrate_value);
		mFatTV =(TextView)activity.findViewById(R.id.food_fat_value);
		mProteinTV =(TextView)activity.findViewById(R.id.food_protein_value);
		mCelluloseTV =(TextView)activity.findViewById(R.id.food_cellulose_value);
		mRemindCB =(CheckBox)activity.findViewById(R.id.remind_time_cb);
		mRemindCB.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean stateB) {
				// TODO Auto-generated method stub
				Log.d("SIMMON","stateB="+stateB);
				 if(stateB){
					 state ="1";
				 }else{
					 state ="0";
				 }
				 connectServierUpdateData();
				
			}
		});
		
		mRemindTime =(TextView)activity.findViewById(R.id.remind_time_tv);
		
		mRemindTimeSet =(ImageButton)activity.findViewById(R.id.remind_time_bt);
		mRemindTimeSet.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				 openSetTimeDialog();
			}
		});
		
		mChangeInfoTv=(TextView)activity.findViewById(R.id.change_info_tv);
		mChangeInfoTv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				connectServierChangeData();
			}
		});

		mDoFlag =(TextView)activity.findViewById(R.id.do_flag_tv);
		mDoFlag.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String result =null;
				if(isCompleted){
					 result = getString(R.string.play_day_info_do_flag_fail);
					activity.openDialogTitle("提示",result,"确定");
				}else{
					final Calendar c = Calendar.getInstance(); 
					 String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));  
					int mWayValue = Integer.valueOf(mWay);
					if(mWayValue==1){
						mWayValue =8;
					}
					Log.d("SIMMON","  mWayValue="+mWayValue);
					Log.d("SIMMON","  weekday="+weekday);
					if((mWayValue -1)==weekday){
						connectServierDoFlagData();
					}else{
						result = getString(R.string.play_day_info_do_flag_error_time);
						activity.openDialogTitle("提示",result,"确定");
					}
				}
			}
		});
		
		
	    connectServierGetData();	
		
	}
	
	private void openSetTimeDialog(){
	    Context context=activity;

	    AlertDialog.Builder builder = new AlertDialog.Builder(context);  
	    View view = View.inflate(context, R.layout.set_time_dialog, null);
	    final TimePicker timePicker =
	            (android.widget.TimePicker) view.findViewById(R.id.time_picker); 
	    builder.setView(view);  
	    Calendar cal = Calendar.getInstance(); 
	    cal.setTimeInMillis(System.currentTimeMillis());  
	    
	    timePicker.setIs24HourView(true);  
	    timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));  
	    timePicker.setCurrentMinute(Calendar.MINUTE); 

	    
	    TextView leftBt =(TextView)view.findViewById(R.id.dialog_self_left_bt);
	    leftBt.setText("取消");
	    leftBt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mDialog.cancel();
			}
		});
	    
	    TextView rightBt =(TextView)view.findViewById(R.id.dialog_self_right_bt);
	    rightBt.setText("确定");
	    rightBt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
                StringBuffer sb = new StringBuffer();
                sb.append(timePicker.getCurrentHour()) 
                .append(":").append(timePicker.getCurrentMinute());
                mRemindTimeNew = sb.toString();
				connectServierUpdateRemindTime();
				mDialog.dismiss();
			}
		});
	    

	    mDialog =builder.create();  
	    mDialog.show();
	}
	

	/**
	 * 渲染界面,显示数据
	 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			//取消加载框
    		if(JSONResult!=null){
    			switch (msg.what) {
				case 0:
				    BindList(JSONResult);
					break;
				case 1:
					UpdateRemind(JSONResult);
					break;
				case 2:
					UpdateRemindTime(JSONResult);
					break;
				case 3:
					UpdatePlanInfoNewData(JSONResult);
					break;
				case 4:
					UpdateDoFlagView(JSONResult);
					break;
				default:
					break;
				}
    		
    		    JSONResult =null;
    		}else{
    			 activity.openDialogBt(NET_ERROR); 
    		}
		}
	};

	private void connectServierGetData(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					GetListData();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Message msg = new Message();
			msg.what =0;
			handler.sendMessage(msg);
			}
		}.start();
	}
	
	private void connectServierUpdateData(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					UpdateRemindState();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Message msg = new Message();
				msg.what =1;
				handler.sendMessage(msg);
			}
		}.start();
	}
	
	private void connectServierUpdateRemindTime(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					UpdateRemindTime();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Message msg = new Message();
				msg.what =2;
				handler.sendMessage(msg);
			}
		}.start();
	}
	
	
	private void connectServierChangeData(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					changeInfoData();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Message msg = new Message();
			msg.what =3;
			handler.sendMessage(msg);
			}
		}.start();
	}
	
	
	private void connectServierDoFlagData(){
		
		new Thread(){
			@Override
			public void run(){
				try {
					doFlagForInfo();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Message msg = new Message();
			msg.what =4;
			handler.sendMessage(msg);
			}
		}.start();
	}
	
	private void  doFlagForInfo() throws IOException
	{

		String httpUrl = com.wehealth.util.GetUrl.Plan_CompleteItem_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 params.add(new BasicNameValuePair("ID",itemID));
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","  JSONResult= "+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	   private void UpdateDoFlagView(String strJSON){
	       try{
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                String  result =   jsonObject.getString("result");
	               if(result.equals("1")){
						    String dialog = getString(R.string.play_day_info_do_flag_sucess);
							activity.openDialog(dialog,"好的");
	               }else{
	            	   activity.openDialogBt(NET_ERROR); 
	               }
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }
	
	
	private void  changeInfoData() throws IOException
	{

		String httpUrl = com.wehealth.util.GetUrl.Plan_ChangeRandomMenu_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 params.add(new BasicNameValuePair("ID",itemID));
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","  JSONResult= "+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	
	   private void UpdatePlanInfoNewData(String strJSON){
	       try{
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                String  result =   jsonObject.getString("result");
	               if(result.equals("1")){
	           	    	connectServierGetData();
	               }else{
	            	   activity.openDialogBt(NET_ERROR); 
	               }
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }
	
	
	private void  UpdateRemindTime() throws IOException
	{

		String httpUrl = com.wehealth.util.GetUrl.Plan_UpdateRemindTime_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 Log.d("SIMMON","  itemID= "+itemID);
		 Log.d("SIMMON","  mRemindTimeNew= "+mRemindTimeNew);
		 params.add(new BasicNameValuePair("id",itemID));
		 params.add(new BasicNameValuePair("time",mRemindTimeNew));
		 
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","  JSONResult= "+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	
	
	private void  UpdateRemindState() throws IOException
	{

		String httpUrl = com.wehealth.util.GetUrl.Plan_UpdateRemindState_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 Log.d("SIMMON","  itemID= "+itemID);
		 params.add(new BasicNameValuePair("id",itemID));
		 params.add(new BasicNameValuePair("state",state));
		 
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","Plan_Day2  JSONResult="+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	   private void UpdateRemindTime(String strJSON){
	       try{
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                String  result =   jsonObject.getString("result");
	               if(result.equals("1")){
	            	    planInfo.setRemindTime(mRemindTimeNew);
	            	    updateRemindTime();
	               }else{
	            	   activity.openDialogBt(NET_ERROR); 
	               }
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }
	
	
	   private void UpdateRemind(String strJSON){
	       try{
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                String  result =   jsonObject.getString("result");
	               if(result.equals("1")){
	            	    planInfo.setisRemind(state);
	            	    updateCheckBoxState();
	               }else{
	            	   activity.openDialogBt(NET_ERROR); 
	               }
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }
	
	
	
	private void  GetListData() throws IOException
	{

		String httpUrl = com.wehealth.util.GetUrl.Plan_GetPlanDetail_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 Log.d("SIMMON","  itemID= "+itemID);
		 params.add(new BasicNameValuePair("id",itemID));
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","Plan_Day  JSONResult="+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	
    //将JSON数据绑定到LISTVIEW
    private void BindList(String strJSON){
       try{
                JSONObject jsonObject = new JSONObject(strJSON); 
                JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );  
                for(int i=0; i<aNews.length(); i++)
                    {
                		planInfo= new DM_PlanDay_info_new();
	                	String planType =aNews.getJSONObject(i).getString("planType");
	                	planInfo.setplanType(planType);
	                	String foodIDs =aNews.getJSONObject(i).getString("foodIDs");
	                	planInfo.setfoodIDs(foodIDs);
	                	String foodNames =aNews.getJSONObject(i).getString("foodNames");
	                	planInfo.setfoodNames(foodNames);
	                	String energy =aNews.getJSONObject(i).getString("energy");
	                	planInfo.setenergye(energy);
	                	String weight =aNews.getJSONObject(i).getString("weight");
	                	planInfo.setweight(weight);
	                	String isRemind =aNews.getJSONObject(i).getString("isRemind");
	                	planInfo.setisRemind(isRemind);
	                	String remindTime =aNews.getJSONObject(i).getString("remindTime");
	                	planInfo.setRemindTime(remindTime);
	                	String sum_carbohydrate =aNews.getJSONObject(i).getString("sum_carbohydrate");
	                	BigDecimal sum_carbohydrate_result = new BigDecimal(sum_carbohydrate);
	                	sum_carbohydrate_result   =   sum_carbohydrate_result.setScale(2,BigDecimal.ROUND_HALF_UP);   
	                	sum_carbohydrate =sum_carbohydrate_result.toString();
	                	planInfo.setSum_carbohydrate(sum_carbohydrate);
	                	String sum_cellulose =aNews.getJSONObject(i).getString("sum_cellulose");
	                	BigDecimal sum_cellulose_result = new BigDecimal(sum_cellulose);
	                	sum_cellulose_result   =   sum_cellulose_result.setScale(2,BigDecimal.ROUND_HALF_UP);   
	                	sum_cellulose =sum_cellulose_result.toString();
	                	planInfo.setSum_cellulose(sum_cellulose);
	                	
	                	String sum_fat =aNews.getJSONObject(i).getString("sum_fat");
	                	BigDecimal sum_fat_result = new BigDecimal(sum_fat);
	                	sum_fat_result   =   sum_fat_result.setScale(2,BigDecimal.ROUND_HALF_UP);   
	                	sum_fat =sum_fat_result.toString();
	                	planInfo.setSum_fat(sum_fat);

	                	String sum_protein =aNews.getJSONObject(i).getString("sum_protein");
	                	BigDecimal sum_protein_result = new BigDecimal(sum_protein);
	                	sum_protein_result   =   sum_protein_result.setScale(2,BigDecimal.ROUND_HALF_UP);   
	                	sum_protein =sum_cellulose_result.toString();
	                	planInfo.setSum_protein(sum_protein);
                }

                updateViewData();
            }
            catch(JSONException ex)
            {
                    Log.e("JSON Error: ", ex.toString()); 
            }
    }
	
    private  void updateViewData(){

    	Adapter_PlanDay_info_new adapter = 
    			new Adapter_PlanDay_info_new(activity,planInfo.getfoodNames(),
    					planInfo.getenergy(),planInfo.getPlanContent());
        lv_planDay.setAdapter(adapter);
        lv_planDay.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int pos, long pos2) {
            	String[] foodIDs =planInfo.getfoodIDs();
            	Plan_day_info_food_descrip  nextScreen = new Plan_day_info_food_descrip(foodIDs[pos]);
            	activity.switchContent(nextScreen);
            }
        });
        
    	mCarbTV.setText(planInfo.getSum_carbohydrate());
    	mFatTV.setText(planInfo.getSum_fat());
    	mProteinTV.setText(planInfo.getSum_protein());
    	mCelluloseTV.setText(planInfo.getSum_cellulose());
    	updateCheckBoxState();
    	updateRemindTime();
    }
    
    private void updateCheckBoxState(){
    	if(planInfo.getisRemind().equals("1")){
    		mRemindCB.setChecked(true);
    	}else{
    		mRemindCB.setChecked(false);
    	}
    	String remindStr = planInfo.getplanType()+"提醒";
    	mRemindCB.setText(remindStr);
    	
    }
    
    private void updateRemindTime(){
    	mRemindTime.setText(planInfo.getRemindTime());
    }
    
    

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPageEnd("Plan_Day"); 
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onPageStart("Plan_Day"); 
    }

    
}
